package com.yh.supergo.user.utils;

import com.yh.supergo.user.pojo.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName JwtUtil
 * @Description Jwt工具类
 * @Author 0715-YuHao
 * @Date 2020/11/26 14:40
 */
@Component
public class JwtUtil {

    @Value("${jwt.config.key}")
    private String key; //密钥

    @Value("${jwt.config.ttl}")
    private long ttl; //过期时间

    /**
     * @Author 0715-YuHao
     * @Description // 生成Jwt Token
     * @Date 2020/11/25 16:48
     * @Param [id, subject, role]
     * @return java.lang.String
     */
    public String generateToken(UserInfo userInfo) {
        JwtBuilder builder = Jwts.builder()
                .setId(userInfo.getId() + "")
                .claim("username", userInfo.getUsername())
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key);
        if (ttl > 0) {
            builder.setExpiration(new Date(System.currentTimeMillis() + ttl * 1000));
        }
        return builder.compact();
    }

    /**
     * @Author 0715-YuHao
     * @Description //解析JWT token
     * @Date 2020/11/25 16:49
     * @Param [token]
     * @return Claims
     */
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }
}
